//
//  IAMetaDataReader.m
//  VoiceClass
//
//  Created by caoxiaobo on 2018/1/1.
//  Copyright © 2018年 YRX. All rights reserved.
//

#import "IAMetaDataReader.h"
#import "IAStudent.h"
#import "IASubjectItem.h"

static dispatch_queue_t subject_data_process_queue() {
    static dispatch_queue_t subject_data_process_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        subject_data_process_queue = dispatch_queue_create("com.meta.data.process", DISPATCH_QUEUE_SERIAL);
    });
    
    return subject_data_process_queue;
}

static dispatch_queue_t result_data_process_queue() {
    static dispatch_queue_t result_data_process_queue;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        result_data_process_queue = dispatch_queue_create("com.meta.data.process", DISPATCH_QUEUE_SERIAL);
    });
    
    return result_data_process_queue;
}

@implementation IAMetaDataReader

#pragma mark - 学生列表

+ (NSArray <IAStudent *> *)getStudents {
    static NSArray *studentArray = nil;
    if (studentArray == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"student" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
        NSMutableArray *arrayM = [NSMutableArray arrayWithCapacity:array.count];
        for (NSDictionary *dictionary in array) {
            IAStudent *stu = [IAStudent studentWithDictionary:dictionary];
            [arrayM addObject:stu];
        }
        studentArray = [arrayM copy];
    }
    return studentArray;
}

#pragma mark - 科目列表

+ (NSArray <NSString *> *)subjectNames {
    static NSArray *subjectNames = nil;
    if (subjectNames == nil) {
        NSString *path = [[NSBundle mainBundle] pathForResource:@"subjects" ofType:@"json"];
        NSData *data = [NSData dataWithContentsOfFile:path];
        subjectNames = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    }
    return subjectNames;
}

#pragma mark - 题目读写

+ (void)getSubjectItemsForName:(NSString *)name
                    completion:(IAMetaDataReaderCompletion)completion {
    if (!completion) {
        return;
    }
    
    dispatch_async(subject_data_process_queue(), ^{
        NSArray *array = [self getSubjectItems];
        NSMutableArray *destArray = [NSMutableArray array];
        [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj[@"subjectName"] isEqualToString:name]) {
                IASubjectItem *subject = [IASubjectItem subjectItemWithDictionary:obj];
                [destArray addObject:subject];
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completion([destArray copy]);
        });
    });
}

+ (NSArray *)getSubjectItems {
    NSString *filePath = [self subjectContentPath];
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    if (!array) {
        array = [self defaultSubjectItems];
        [array writeToFile:filePath atomically:YES];
    }
    return array;
}

+ (void)saveSubject:(IASubjectItem *)subject
         completion:(IAMetaDataCompletion)completion {
    if (!subject || !completion) {
        return;
    }
    NSString *filePath = [self subjectContentPath];
    /** 根据业务逻辑 所以这里 needUpdate 可以传NO 这样读取效率高一些
     * 如果以后由业务变更 需要重新梳理逻辑
     */
    dispatch_async(subject_data_process_queue(), ^{
        NSMutableArray *arrayMutable = [[self getSubjectItems] mutableCopy];
        if (!arrayMutable) {
            arrayMutable = [NSMutableArray array];
        }
        NSDictionary *subDictionary = @{@"question": subject.question ?: @"",
                                        @"answer": subject.answer ?: @"",
                                        @"subjectName": subject.subjectName ?: @"地理"};
        [arrayMutable addObject:subDictionary];
        BOOL r = [arrayMutable writeToFile:filePath atomically:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(r);
        });
    });
}

+ (NSString *)subjectContentPath {
    static NSString *subjectContentPath = nil;
    if (subjectContentPath == nil) {
        NSString *homeDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        subjectContentPath = [homeDirectoryPath stringByAppendingPathComponent:@"subjectContent.plist"];
    }
    return subjectContentPath;
}

+ (NSArray *)defaultSubjectItems {
    NSString *path = [[NSBundle mainBundle] pathForResource:@"content" ofType:@"json"];
    NSData *data = [NSData dataWithContentsOfFile:path];
    NSArray *array = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
    return array;
}

#pragma mark - 答题结果读写

+ (NSArray <IASubjectAnswerResult *> *)getSubjectResultsOfQuestion:(NSString *)question {
    if (!question) {
        return nil;
    }
    NSArray *array = [self getAllSubjectResultsDictionay];
    NSMutableArray *destArray = [NSMutableArray array];
    [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        if ([obj[@"question"] isEqualToString:question]) {
            IASubjectAnswerResult *result = [self resultFromDictionary:obj];
            [destArray addObject:result];
        }
    }];
    return [destArray copy];
}

+ (void)getSubjectResultsForName:(NSString *)name
                      completion:(IAMetaDataReaderCompletion)completion {
    if (!completion) {
        return;
    }
    dispatch_async(result_data_process_queue(), ^{
        NSArray *array = [self getAllSubjectResultsDictionay];
        NSMutableArray *destArray = [NSMutableArray array];
        [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj[@"subjectName"] isEqualToString:name]) {
                IASubjectAnswerResult *result = [self resultFromDictionary:obj];
                [destArray addObject:result];
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completion([destArray copy]);
        });
    });
}

+ (void)getSubjectResultsForStudent:(NSString *)studentID
                         completion:(IAMetaDataReaderCompletion)completion {
    if (!completion) {
        return;
    }
    dispatch_async(result_data_process_queue(), ^{
        NSArray *array = [self getAllSubjectResultsDictionay];
        NSMutableArray *destArray = [NSMutableArray array];
        [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            if ([obj[@"studentID"] isEqualToString:studentID]) {
                IASubjectAnswerResult *result = [self resultFromDictionary:obj];
                [destArray addObject:result];
            }
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completion([destArray copy]);
        });
    });
}

+ (void)getAllSubjectResultsWithCompletion:(IAMetaDataReaderCompletion)completion {
    if (!completion) {
        return;
    }
    dispatch_async(result_data_process_queue(), ^{
        NSArray *array = [self getAllSubjectResultsDictionay];
        NSMutableArray *destArray = [NSMutableArray array];
        [array enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL * _Nonnull stop) {
            IASubjectAnswerResult *result = [self resultFromDictionary:obj];
            [destArray addObject:result];
        }];
        dispatch_async(dispatch_get_main_queue(), ^{
            completion([destArray copy]);
        });
    });
}

+ (NSArray <NSDictionary *> *)getAllSubjectResultsDictionay {
    NSString *filePath = [self subjectResultsContentPath];
    NSArray *array = [NSArray arrayWithContentsOfFile:filePath];
    return array;
}

+ (void)saveSubjectResult:(IASubjectAnswerResult *)result
               completion:(IAMetaDataCompletion)completion {
    if (!result || !completion) {
        return;
    }
    NSString *filePath = [self subjectResultsContentPath];
    dispatch_async(result_data_process_queue(), ^{
        NSMutableArray *arrayMutable = [[self getAllSubjectResultsDictionay] mutableCopy];
        if (!arrayMutable) {
            arrayMutable = [NSMutableArray array];
        }
        NSDictionary *subDictionary = [self dictionaryFromResult:result];
        [arrayMutable addObject:subDictionary];
        BOOL r = [arrayMutable writeToFile:filePath atomically:YES];
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(r);
        });
    });
    
}

+ (NSString *)subjectResultsContentPath {
    static NSString *subjectResultsContentPath = nil;
    if (subjectResultsContentPath == nil) {
        NSString *homeDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        subjectResultsContentPath = [homeDirectoryPath stringByAppendingPathComponent:@"subjectResults.plist"];
    }
    return subjectResultsContentPath;
}

+ (long long)getAllSubjectResultsBytes {
    NSString *filePath = [self subjectResultsContentPath];
    NSFileManager* manager =[NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
    }
    return 0;
}

+ (void)removeAllSubjectResultsBytesWithCompletion:(IAMetaDataCompletion)completion {
    NSString *filePath = [self subjectResultsContentPath];
    NSFileManager* manager =[NSFileManager defaultManager];
    if ([manager fileExistsAtPath:filePath]){
        dispatch_async(result_data_process_queue(), ^{
            BOOL r = [manager removeItemAtPath:filePath error:nil];
            if (completion) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    completion(r);
                });
            }
        });
    }
}

+ (IASubjectAnswerResult *)resultFromDictionary:(NSDictionary *)dictionary {
    IASubjectAnswerResult *result = [[IASubjectAnswerResult alloc] init];
    IASubjectItem *subject = [IASubjectItem subjectItemWithDictionary:dictionary];
    IAStudent *student = [IAStudent studentWithDictionary:dictionary];
    result.subjectItem = subject;
    result.student = student;
    result.studentAnswer = dictionary[@"studentAnswer"];
    result.goal = dictionary[@"goal"];
    return result;
}

+ (NSDictionary *)dictionaryFromResult:(IASubjectAnswerResult *)result {
    NSDictionary *subDictionary = @{@"question": result.subjectItem.question ?: @"",
                                    @"answer": result.subjectItem.answer ?: @"",
                                    @"studentAnswer":result.studentAnswer,
                                    @"subjectName": result.subjectItem.subjectName ?: @"地理",
                                    @"studentName":result.student.name,
                                    @"studentID":result.student.stuID,
                                    @"goal" : result.goal ?: @"0",
                                    @"avatar" : result.student.avatar,
                                    @"studentGrade" : result.student.grade,
                                    };
    return subDictionary;
}

@end
